from drf_haystack.serializers import HaystackSerializer
from rest_framework import serializers
from .search_indexes import HouseListingIndex

class HouseListingIndexSerializer(HaystackSerializer):
    # 显式定义字段
    orientation = serializers.CharField(default='未知')
    deposit = serializers.CharField(default='0')
    landlord = serializers.CharField(default='未知')
    id = serializers.IntegerField()
    title = serializers.CharField()
    address = serializers.CharField()
    city = serializers.CharField()
    description = serializers.CharField()
    facilities = serializers.CharField()
    price = serializers.CharField()
    area = serializers.CharField()

    class Meta:
        index_classes = [HouseListingIndex]
        fields = [
            "text",
            "id",
            "title",
            "address",
            "price",
            "area",
            "description",
            "facilities",
            "orientation",
            "deposit",
            "landlord",
            "city"
        ]

    def get_orientation(self, obj):
        # 处理朝向字段
        try:
            return obj.orientation or '未知'
        except AttributeError:
            return '未知'

    def get_deposit(self, obj):
        # 处理押金字段
        try:
            return obj.deposit or '0'
        except AttributeError:
            return '0'

    def get_landlord(self, obj):
        # 处理房东字段
        try:
            return obj.landlord or '未知'
        except AttributeError:
            return '未知'

    def to_representation(self, instance):
        # 重写序列化方法
        try:
            data = super().to_representation(instance)
        except AttributeError:
            data = {
                'text': instance.text,
                'id': instance.id,
                'title': instance.title,
                'address': instance.address,
                'price': instance.price,
                'area': instance.area,
                'description': instance.description,
                'facilities': instance.facilities,
                'orientation': self.get_orientation(instance),
                'deposit': self.get_deposit(instance),
                'landlord': self.get_landlord(instance),
                'city': instance.city
            }
        return data 